package com.erp.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.user.domain.City;
import com.erp.user.domain.bo.CityBo;
import com.erp.user.domain.vo.CityVo;
import com.erp.user.mapper.CityMapper;
import com.erp.user.service.ICityService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 城市Service业务层处理
 *
 * @author erp
 * @date 2023-05-08
 */
@RequiredArgsConstructor
@Service
public class CityServiceImpl implements ICityService {

    private final CityMapper baseMapper;

    /**
     * 查询城市
     */
    @Override
    public CityVo queryById(Integer id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询城市列表
     */
    @Override
    public TableDataInfo<CityVo> queryPageList(CityBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<City> lqw = buildQueryWrapper(bo);
        Page<CityVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询城市列表
     */
    @Override
    public List<CityVo> queryList(CityBo bo) {
        LambdaQueryWrapper<City> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<City> buildQueryWrapper(CityBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<City> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), City::getCity, bo.getCity());
        lqw.eq(bo.getProvinceId() != null, City::getProvinceId, bo.getProvinceId());
        return lqw;
    }

    /**
     * 新增城市
     */
    @Override
    public Boolean insertByBo(CityBo bo) {
        City add = BeanUtil.toBean(bo, City.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改城市
     */
    @Override
    public Boolean updateByBo(CityBo bo) {
        City update = BeanUtil.toBean(bo, City.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(City entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除城市
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Integer> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
